class BingoController < ApplicationController

  CENTER_SQUARE_POSITION = 12
  FIRST_SQUARE_POSITION = 0
  NUMBER_OF_SQUARES = 25

  # Returns 25 (or fewer) random arguments, including the ones requested via :include_these
  def index
    @new_entry = params[:new_entry] || []
    @preselected_ids = params[:include_these] || @new_entry
    @preselected_ids.collect!{|elem| elem.to_i}
    @preselected_ids.uniq!
    start_pos = params[:start_position].to_i || FIRST_SQUARE_POSITION

    if @preselected_ids.length < NUMBER_OF_SQUARES
      # Get only arguments in the current locale
      if Locale.active
        ids_from_db = Argument.find(:all, 
                                    :conditions => [ 'language_id = ?', Locale.active.language.id ],
                                    :select => "id").map(&:id)
      else
        ids_from_db = Argument.find(:all, :select => "id").map(&:id)
      end

      if ids_from_db.length > 0
        ids_from_db.delete_if { |elem| @preselected_ids.include?(elem) }
        randomlyselected_ids = ids_from_db.sort_by{rand}.first(NUMBER_OF_SQUARES-@preselected_ids.length)
        arguments_preselected = Argument.find(:all, :conditions => ["id IN (?)", @preselected_ids])
        @arguments = Argument.find(:all, :conditions => ["id IN (?)", randomlyselected_ids])
        @arguments.insert(start_pos, arguments_preselected).flatten!
        @arguments.fill(nil, @arguments.length, NUMBER_OF_SQUARES-@arguments.length)
      else
        # no arguments in database, return empty array
        @arguments=[]
      end
    else
      @preselected_ids.slice!(NUMBER_OF_SQUARES..@preselected_ids.length)
      @arguments = Argument.find(:all, :conditions => ["id IN (?)", @preselected_ids])
    end
  end

  # Calls the random_response method on a selected argument
  def show
    @argument = Argument.find(params[:id])
    @response = @argument.random_response
    render :partial => @show
  end
end
